package jsp.servlet;

import jsp.model.User;
import jsp.servcie.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userUpdate")
public class UserUpdateServlet extends HttpServlet {

    private UserService service = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("admin");

        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setName(name);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        service.update(user);

        response.sendRedirect(request.getContextPath() + "/userList");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        User user = service.getById(Integer.parseInt(id));
        request.setAttribute("user", user);
        request.getRequestDispatcher(request.getContextPath() + "/userUpdate.jsp").forward(request, response);
    }
}
